"""Deep health check with dependency validation (OBS-04).

/health           — liveness only, fast & cheap (for Docker/ELB)
/health/ready     — readiness: validates MCP reachability + LLM key presence
"""
import logging
import os
import time
from typing import Any

import httpx
from fastapi import APIRouter, Response, status

logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="",
    tags=["health"],
)


@router.get("/health")
async def liveness() -> dict[str, Any]:
    return {"status": "OK", "service": "eugene-agent-ws"}


@router.get("/health/ready")
async def readiness(response: Response) -> dict[str, Any]:
    checks: dict[str, dict[str, Any]] = {}
    overall_ok = True

    # 1. LLM provider: at least one API key must be present
    has_anthropic = bool(os.environ.get("ANTHROPIC_API_KEY"))
    has_openai = bool(os.environ.get("OPENAI_API_KEY"))
    checks["llm_provider"] = {
        "ok": has_anthropic or has_openai,
        "anthropic": has_anthropic,
        "openai": has_openai,
    }
    overall_ok &= checks["llm_provider"]["ok"]

    # 2. MCP server reachability
    mcp_url = os.environ.get("EUGENE_MCP_SERVER_URL", "")
    if mcp_url:
        start = time.perf_counter()
        try:
            # Probe the root of the MCP server (strip /mcp suffix if present)
            probe_url = mcp_url.rstrip("/")
            if probe_url.endswith("/mcp"):
                probe_url = probe_url[:-4]
            verify_ssl = os.environ.get("EUGENE_MCP_VERIFY_SSL", "true").lower() != "false"
            async with httpx.AsyncClient(verify=verify_ssl, timeout=3.0) as client:
                resp = await client.get(f"{probe_url}/health")
            checks["mcp"] = {
                "ok": resp.status_code < 500,
                "status_code": resp.status_code,
                "latency_ms": int((time.perf_counter() - start) * 1000),
            }
        except Exception as exc:
            checks["mcp"] = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
        overall_ok &= checks["mcp"]["ok"]
    else:
        checks["mcp"] = {"ok": False, "error": "EUGENE_MCP_SERVER_URL not set"}
        overall_ok = False

    # 3. JWT signing secret configured
    secret_configured = bool(os.environ.get("EUGENE_CLIENT_SECRET"))
    checks["jwt_secret"] = {"ok": secret_configured}
    overall_ok &= secret_configured

    if not overall_ok:
        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE

    return {
        "status": "OK" if overall_ok else "DEGRADED",
        "service": "eugene-agent-ws",
        "checks": checks,
    }
